<!doctype html>
<html>
<head>
    <meta charset="utf-8">
<title>JS重力球效果</title>
<style>
    *{
        margin:0px;
        padding:0px;
    }
    #box{
        width:30px;
        height:30px;
        background:#f90;
        position:absolute;
        cursor:pointer;
        border-radius:50%;
        box-shadow: 0px 0px 5px #000;
    }
</style>

</head>
<body>
    <div id='box'></div>

<script>
window.onload = function () {

    var oDiv = document.getElementById('box');
    var lastX = 0;
    var lastY = 0;
    oDiv.onmousedown = function(ev) {
        var ev = ev || event;
        var disX = ev.pageX - oDiv.offsetLeft;
        var disY = ev.pageY - oDiv.offsetTop;
        document.onmousemove = function(ev) {
            var ev = ev || event;
            var l = ev.pageX - disX;
            var t = ev.pageY - disY;
            oDiv.style.left = l + 'px';
            oDiv.style.top = t + 'px';
            iSpeedX = l - lastX;
            iSpeedY = t - lastY;
            lastX = l;
            lastY = t;
        }
        document.onmouseup = function() {
            document.onmousemove = null;
            document.onmouseup = null;
            startMove();
        }
    }

    
    clearInterval(timer);
    var timer = null;

    function startMove() {
        var nowX = oDiv.offsetLeft;
        var nowY = oDiv.offsetTop;
        clearInterval(timer);
        timer = setInterval(function() {
            iSpeedY += 5;
            nowX += iSpeedX;
            if (nowX > document.documentElement.clientWidth - oDiv.offsetWidth) {
                iSpeedX *= -0.8;
                nowX = document.documentElement.clientWidth - oDiv.offsetWidth;
            } else if (nowX < 0) {
                iSpeedX *= -0.8;
                nowX = 0;
            }
            nowY += iSpeedY;
            if (nowY > document.documentElement.clientHeight - oDiv.offsetHeight) {
                iSpeedY *= -0.8;
                iSpeedX *= 0.8;
                nowY = document.documentElement.clientHeight - oDiv.offsetHeight;
            } else if (nowY < 0) {
                iSpeedY *= -1;
                iSpeedX *= 0.8;
                nowY = 0;
            }
            if (Math.abs(iSpeedX) < 1) {
                iSpeedX = 0;
            }
            if (Math.abs(iSpeedY) < 1) {
                iSpeedY = 0;
            }
            if (iSpeedX == 0 && iSpeedY == 0 && nowY == document.documentElement.clientHeight - oDiv.offsetHeight) {
                clearInterval(timer);
            }
            oDiv.style.left = nowX + 'px';
            oDiv.style.top = nowY + 'px';
        }, 30);
    }
}
</script>
</body>
</html>